package com.chuangke.common.idgen.orderid;

import cn.hutool.core.util.StrUtil;
import com.chuangke.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class OrderIdWorker {
	
	public static final String CACHE_REGIN = "ORDER-ID" ;
	
	@Autowired
	private CacheManager cacheManager;
	

	public synchronized String nextId(String bisNo) {
		return nextId(bisNo,4) ;
	}

	public synchronized String nextId(String bisNo,int length) {
		String cacheKey = bisNo + DateUtils.getDate(new Date(), "yyyyMMdd") ;

		ValueWrapper vw = cacheManager.getCache(CACHE_REGIN).get(cacheKey) ;
		Integer step = vw == null ? 1 : (Integer)vw.get()  ;

		StringBuilder id = new StringBuilder() ;
		id.append(bisNo);//.append("-") ;
		id.append(DateUtils.getDate(new Date(), "yyyyMMdd"));//.append("-") ;
		id.append(StrUtil.fillBefore(step+"",'0',length)) ;

		step++ ;

		cacheManager.getCache(CACHE_REGIN).put(cacheKey, step);

		return id.toString();
	}

	public synchronized String nextSn(String bisNo,int length) {
		String cacheKey = bisNo + DateUtils.getDate(new Date(), "yyyyMMdd") ;

		ValueWrapper vw = cacheManager.getCache(CACHE_REGIN).get(cacheKey) ;
		Integer step = vw == null ? 1 : (Integer)vw.get()  ;

		String sn = StrUtil.fillBefore(step+"",'0',length) ;

		step++ ;

		cacheManager.getCache(CACHE_REGIN).put(cacheKey, step);

		return sn;
	}
}
